import React, { createContext, useReducer, useEffect, type ReactNode } from 'react';
import { type UserInfo, UserRole, Permission, ROLE_PERMISSIONS, type AuthState } from '../types/auth';

// 认证状态类型
type AuthAction = 
  | { type: 'LOGIN_START' }
  | { type: 'LOGIN_SUCCESS'; payload: UserInfo }
  | { type: 'LOGIN_FAILURE'; payload: string }
  | { type: 'LOGOUT' }
  | { type: 'CLEAR_ERROR' }
  | { type: 'REFRESH_TOKEN'; payload: string };

// 初始状态
const initialState: AuthState = {
  isAuthenticated: false,
  user: null,
  loading: false,
  error: null
};

// 认证状态reducer
const authReducer = (state: AuthState, action: AuthAction): AuthState => {
  switch (action.type) {
    case 'LOGIN_START':
      return {
        ...state,
        loading: true,
        error: null
      };
    case 'LOGIN_SUCCESS':
      return {
        ...state,
        isAuthenticated: true,
        user: action.payload,
        loading: false,
        error: null
      };
    case 'LOGIN_FAILURE':
      return {
        ...state,
        isAuthenticated: false,
        user: null,
        loading: false,
        error: action.payload
      };
    case 'LOGOUT':
      return {
        ...state,
        isAuthenticated: false,
        user: null,
        loading: false,
        error: null
      };
    case 'CLEAR_ERROR':
      return {
        ...state,
        error: null
      };
    case 'REFRESH_TOKEN':
      return {
        ...state,
        user: state.user ? {
          ...state.user,
          accessToken: action.payload
        } : null
      };
    default:
      return state;
  }
};

// 认证上下文类型
export interface AuthContextType {
  state: AuthState;
  login: (userInfo: UserInfo) => void;
  logout: () => void;
  refreshToken: () => Promise<boolean>;
  hasPermission: (permission: Permission) => boolean;
  hasRole: (role: UserRole) => boolean;
  clearError: () => void;
}

// 创建认证上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// Token管理工具函数
const TOKEN_KEY = 'wechatAccessToken';
const TOKEN_EXPIRY_KEY = 'tokenExpiry';

// 检查token是否过期
const isTokenExpired = (): boolean => {
  const expiry = localStorage.getItem(TOKEN_EXPIRY_KEY);
  if (!expiry) return true;
  
  const expiryTime = parseInt(expiry, 10);
  return Date.now() >= expiryTime;
};

// 设置token和过期时间
const setToken = (token: string, expiresIn: number = 7200) => {
  const expiryTime = Date.now() + (expiresIn * 1000);
  localStorage.setItem(TOKEN_KEY, token);
  localStorage.setItem(TOKEN_EXPIRY_KEY, expiryTime.toString());
};

// 获取token
const getToken = (): string | null => {
  if (isTokenExpired()) {
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(TOKEN_EXPIRY_KEY);
    return null;
  }
  return localStorage.getItem(TOKEN_KEY);
};

// 模拟token刷新API
const refreshTokenAPI = async (): Promise<{ success: boolean; token?: string; message?: string }> => {
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 500));
  
  // 模拟90%成功率
  if (Math.random() > 0.1) {
    const newToken = `refreshed_token_${Date.now()}`;
    return { success: true, token: newToken };
  } else {
    return { success: false, message: 'Token刷新失败' };
  }
};

// 认证提供者组件
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, initialState);

  // 从localStorage恢复用户状态
  useEffect(() => {
    const savedUser = localStorage.getItem('userInfo');
    
    if (savedUser) {
      try {
        const userInfo: UserInfo = JSON.parse(savedUser);
        const token = getToken();
        
        console.log('恢复用户状态:', { userInfo, token });
        
        // 如果有有效token，使用它；否则使用保存的token
        if (token) {
          userInfo.accessToken = token;
        }
        
        // 确保用户信息有正确的角色和权限
        if (!userInfo.role) {
          userInfo.role = userInfo.nickname.includes('admin') || userInfo.openid.includes('admin') 
            ? UserRole.ADMIN 
            : UserRole.USER;
        }
        
        if (!userInfo.permissions) {
          userInfo.permissions = ROLE_PERMISSIONS[userInfo.role];
        }
        
        dispatch({ type: 'LOGIN_SUCCESS', payload: userInfo });
        console.log('用户状态恢复成功');
      } catch (error) {
        console.error('Failed to parse saved user info:', error);
        localStorage.removeItem('userInfo');
        localStorage.removeItem(TOKEN_KEY);
        localStorage.removeItem(TOKEN_EXPIRY_KEY);
      }
    } else {
      console.log('没有找到保存的用户信息');
    }
  }, []);

  // 自动刷新token
  useEffect(() => {
    if (!state.isAuthenticated || !state.user) return;

    const checkAndRefreshToken = async () => {
      const token = getToken();
      if (!token) {
        // Token已过期，尝试刷新
        const result = await refreshTokenAPI();
        if (result.success && result.token) {
          setToken(result.token);
          dispatch({ type: 'REFRESH_TOKEN', payload: result.token });
        } else {
          // 刷新失败，登出用户
          logout();
        }
      }
    };

    // 延迟5秒后开始检查，避免页面刷新时立即检查
    const initialDelay = setTimeout(() => {
      checkAndRefreshToken();
    }, 5000);

    // 每5分钟检查一次token
    const interval = setInterval(checkAndRefreshToken, 5 * 60 * 1000);

    return () => {
      clearTimeout(initialDelay);
      clearInterval(interval);
    };
  }, [state.isAuthenticated, state.user]);

  // 登录函数
  const login = (userInfo: UserInfo) => {
    dispatch({ type: 'LOGIN_START' });
    
    // 模拟API调用延迟
    setTimeout(() => {
      // 根据用户信息分配角色（这里可以根据实际业务逻辑调整）
      const role = userInfo.nickname.includes('admin') || userInfo.openid.includes('admin') 
        ? UserRole.ADMIN 
        : UserRole.USER;
      
      const userWithRole: UserInfo = {
        ...userInfo,
        id: userInfo.openid,
        role,
        permissions: ROLE_PERMISSIONS[role]
      };
      
      // 保存到localStorage
      localStorage.setItem('userInfo', JSON.stringify(userWithRole));
      setToken(userInfo.accessToken || `token_${Date.now()}`);
      
      dispatch({ type: 'LOGIN_SUCCESS', payload: userWithRole });
    }, 1000);
  };

  // 登出函数
  const logout = () => {
    localStorage.removeItem('userInfo');
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(TOKEN_EXPIRY_KEY);
    dispatch({ type: 'LOGOUT' });
  };

  // 手动刷新token
  const refreshToken = async (): Promise<boolean> => {
    try {
      const result = await refreshTokenAPI();
      if (result.success && result.token) {
        setToken(result.token);
        dispatch({ type: 'REFRESH_TOKEN', payload: result.token });
        return true;
      } else {
        logout();
        return false;
      }
    } catch (error) {
      console.error('Token刷新失败:', error);
      logout();
      return false;
    }
  };

  // 检查权限
  const hasPermission = (permission: Permission): boolean => {
    if (!state.user) return false;
    return state.user.permissions.includes(permission);
  };

  // 检查角色
  const hasRole = (role: UserRole): boolean => {
    if (!state.user) return false;
    return state.user.role === role;
  };

  // 清除错误
  const clearError = () => {
    dispatch({ type: 'CLEAR_ERROR' });
  };

  const value: AuthContextType = {
    state,
    login,
    logout,
    refreshToken,
    hasPermission,
    hasRole,
    clearError
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

// 导出AuthContext供useAuth Hook使用
export { AuthContext }; 